package com.example.stock.business;

import com.example.stock.controller.dto.WuguDTO;
import com.example.stock.controller.vo.StockInfoVO;
import com.example.stock.excel.LevelPointDecrease;
import com.example.stock.excel.Wugu;
import com.example.stock.model.DailyDetail;
import com.example.stock.model.WeekDetail;
import com.example.stock.service.*;
import com.example.stock.util.NumberUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class WuguBusiness {

    @Autowired
    WuguService wuguService;

    @Autowired
    MonthDataService monthDataService;

    @Autowired
    WeekDataService weekDataService;

    @Autowired
    DailyDataService dailyDataService;

    @Autowired
    StockService stockService;

    @Cacheable(value = "getWuguDTO")
    public List<WuguDTO> getWuguDTO() {
        List<Wugu> wuguList = wuguService.getWuguList();

        Map<String, LevelPointDecrease> lpMap = monthDataService.getCurrentLevelPointDecreaseMap();

        List<WuguDTO> ret = new ArrayList<>();
        wuguList.forEach(wugu -> {
            WuguDTO wuguDTO = new WuguDTO();
            BeanUtils.copyProperties(wugu, wuguDTO);

            WeekDetail currentWeekDetail = weekDataService.getCurrentWeekDetail(wugu.getStock());
            if (Objects.isNull(currentWeekDetail)) {
                return;
            }
            wuguDTO.setLp(currentWeekDetail.getLp());
            wuguDTO.setRelLp(currentWeekDetail.getRelLP());
            if (currentWeekDetail.getPbRatio() != null) {
                wuguDTO.setPbRatio(NumberUtil.floor(currentWeekDetail.getPbRatio(), 2));
            }
            if (currentWeekDetail.getPeRatio() != null) {
                wuguDTO.setPeRatio(NumberUtil.floor(currentWeekDetail.getPeRatio(), 2));
            }

            // 股息
            StockInfoVO stockInfo = stockService.getStockInfo(wugu.getStock());
            wuguDTO.setDividendYield(NumberUtil.floor(stockInfo.getDividendYield(), 2));

            LevelPointDecrease levelPointDecrease = lpMap.get(wugu.getStock());
            if (levelPointDecrease != null) {
                wuguDTO.setLpDuration(Optional.ofNullable(levelPointDecrease.getLpDuration()).orElse(0));
                wuguDTO.setLpDecrease(Optional.ofNullable(levelPointDecrease.getLpDecrease()).orElse(0.0));
            }

            // 成交量 rank 数据
            DailyDetail lastTradingRankByStock = dailyDataService.getLastedDailyDetailByStock(wugu.getStock());
            if (lastTradingRankByStock != null) {
                /*
                wuguDTO.setMoneyRank(lastTradingRankByStock.getMoneyRank());
                wuguDTO.setVolumeRank(lastTradingRankByStock.getVolumeRank());
                 */
            }

            ret.add(wuguDTO);
        });

        return ret;
    }
}
